const Help = require("./help.js");
const path = require("path");
async function  main(){
  global["json_exe_dir"]=path.dirname(process.argv[0]) //正式运行的路径
  if(process.env.debugENV === 'debug'){
    global["json_exe_dir"]=path.dirname(process.argv[1])//调试用的路径
  }
  global["json_last_msg"]=""
  if(!global["json_config"]){
    global["json_config"]=require("./config.js");   
  }
  //init
  {
    if(!global["class_rabbitmq"]){
      await Help.Init_RabbitMQ()
    }
    if(!global["class_s3"]){
      await Help.Init_S3()
    }
  }
  Help.add_consume_process();
  if(global["class_rabbitmq"]){
    await Help.consume_rabbitmq()
  }
  await init_server();
  Help.Console_log("start ...")
}
async function  init_server(){
  const http = require('http');
  const Koa = require("koa"); 
  const bodyparser = require("koa-bodyparser");
  const json = require("koa-json");
  const static = require('koa-static');
  const app = new Koa();
  return new Promise((resolve)=>{
    app.use(async (ctx, next) => {
      ctx.set("Access-Control-Allow-Origin", "*")
      ctx.set("Access-Control-Allow-Methods","POST, GET");
      ctx.set("Access-Control-Allow-Headers","x-requested-with,authorization,Content-Type,Accept,client,Aworker");
      if (ctx.request.method == "OPTIONS") {ctx.response.status = 200;}
      else {
        try {await next();} 
        catch (err) {
          ctx.response.status = err.statusCode || err.status || 500;
          ctx.response.body = {message: err.message}
        }
      }
    });
    //获取post传过来的参数
    app.use(bodyparser({
      enableTypes: ["json", "form", "text"],
      encoding:'utf-8', //限制上传的数据量
      formLimit:'50mb',
      jsonLimit:'50mb',
      textLimit:'50mb',
      strict:true,
      detectJSON:null,
      multipart: true,
      extendTypes:{
        json: ['application/x-javascript'], 
      },
      onerror:function (err, ctx) {
        ctx.throw('body parse error', 422);
      }
    }));
    app.use(json());
    // app.use(historyApiFallback({ 
    //   whiteList: ['/task'],
    //   index: '/index.html'
    // }));
    // app.use(static(`${global["json_exe_dir"]}/html`)); 
    const router_wmts_con= require("./www/wmts_con.js")
    app.use(router_wmts_con.routes(), router_wmts_con.allowedMethods());
    const server= http.createServer(app.callback());
    server.on("error", async (error)=> {
      Help.Console_log(`创建服务器失败:${error.message}`)
      resolve(false)
    });
    server.on("listening", async()=> {
      let addr = server.address();
      Help.Console_log(`http://127.0.0.1:${addr.port}`)
      resolve(true)
    });
    server.listen(global["json_config"]?.port);
  })
}
main().then(()=>{

})